package com.example.cardgame

import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.children
import com.example.cardgame.databinding.ActivityMainBinding


class FristActivity : AppCompatActivity() ,View.OnClickListener{

    private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    lateinit var  game: CardMatchingGame
    val cardButtons = mutableListOf<Button>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        for (v in binding.gridLayout.children){
            if (v is Button){
                v.setOnClickListener (this)
                cardButtons.add(v)
            }
        }
        game = CardMatchingGame(cardButtons.count())
        updateUI()

        binding.Reset.setOnClickListener {
                game=CardMatchingGame(cardButtons.count())
            updateUI()

        }
        binding.button4.setOnClickListener {
            finish()
        }


    }

    fun updateUI() {
        for (button in cardButtons){
            val index = cardButtons.indexOf(button)
            val card = game.cardAtIndex(index)
            button.isEnabled = !card.isMatched
            if (card.isChosen) {
                button.text = card.toString()
                button.setBackgroundColor(R.drawable.bai)
            }
            else{
                button.text = ""
                button.setBackgroundResource(R.drawable.img)
            }
        }
        binding.score.text = String.format("%s%d","Score:",game.score)
    }

    override fun onClick(v: View?) {
        if (v is Button){
            val index = cardButtons.indexOf(v)
            game.chooseCardAtIndex(index)
            updateUI()
        }
    }


}
